import React, { Component } from 'react'

export default class Counter extends Component {

    state = {
        count: 0
    }
 
    // 自增
    increment = () => {
        let num = this.refs.numSelect.value * 1;
        let count = this.state.count + num;
        this.setState({count})
    }

    decrement = () => {
        let num = this.refs.numSelect.value * 1;
        let count = this.state.count - num;
        this.setState({count})
    }   

    
    incrementIfOdd = () => {
        let count = this.state.count;
        if (count % 2 === 0) {
            let num = this.refs.numSelect.value * 1;
            count += num;
            this.setState({count})
        }
    }

    
    incrementAsync = () => {
        setTimeout(() => {
            const num = this.refs.numSelect.value*1
            const count = this.state.count + num
            this.setState({count})
          }, 1000)
    }


    render() {
        let {count}= this.state
        return (
            <div>
                <p>Click { count } times</p>
                
                <div>
                    <select ref="numSelect">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                    &nbsp;&nbsp;
                    <button onClick={this.increment}>+</button>&nbsp;&nbsp;
                    <button onClick={this.decrement}>-</button>&nbsp;&nbsp;
                    <button onClick={this.incrementIfOdd}>increment if odd</button>&nbsp;&nbsp;
                    <button onClick={this.incrementAsync}>increment async</button>
                </div>
            </div>
        )
    }

}